from os.path import exists

from django.http import JsonResponse
from django.shortcuts import redirect,render
from web import models as wm
from utils.group import Option,NbSearchGroup
from utils.pager import Pagination
from django.db.models import Q
from web.forms.customer_form import *
from django.db import transaction
from utils.Baseresponse import BaseResponse

def customer_list(request):
    search_group = NbSearchGroup(
        request,
        wm.Customer,
        Option('level',db_condition={'active':1})
    )

    keyword = request.GET.get('keyword','').strip()

    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('username__contains',keyword))
        con.children.append(('mobile__contains',keyword))
        con.children.append(('level__title__contains',keyword))

    queryset = wm.Customer.objects.filter(con).filter(active=1).filter(**search_group.get_condition).select_related('level')

    obj = Pagination(request,queryset)

    context = {
        'queryset':queryset[obj.start:obj.end],
        'page_string':obj.html(),
        'keyword':keyword,
        'search_group':search_group,
    }
    return render(request,'customer_list.html',context)

def customer_add(request):
    if request.method == 'GET':
        form = CustomerAddForm()
        return render(request,'form2.html',{'form':form})

    form = CustomerAddForm(request.POST)
    if not form.is_valid():
        return render(request,'form2.html',{'form':form})

    # 创建者id
    form.instance.creator_id = request.fc_user.id
    form.save()
    return redirect('customer_list')

def customer_edit(request,pk):
    customer_obj = wm.Customer.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = CustomerAddForm(instance=customer_obj)
        return render(request,'form2.html',{'form':form})

    form = CustomerAddForm(instance=customer_obj,data=request.POST)
    if not form.is_valid():
        return render(request,'form2.html',{'form':form})

    form.save()
    return redirect('customer_list')

def customer_delete(request):
    cid = request.GET.get('cid',0)
    if not cid:
        res = BaseResponse(status=False,detail="请选择删除数据")
        return JsonResponse(res.dict)

    exists = wm.Customer.objects.filter(id=cid).first()
    if not exists:
        res = BaseResponse(status=False,detail="删除数据不存在")
        return JsonResponse(res.dict)

    wm.Customer.objects.filter(id=cid).update(active=0)
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)

def customer_reset(request,pk):
    if request.method == 'GET':
        form = CustomerResetForm()
        return render(request,'form2.html',{'form':form})
    customer_obj = wm.Customer.objects.filter(id=pk).first()
    form = CustomerResetForm(instance=customer_obj,data=request.POST)
    if not form.is_valid():
        return render(request,'form2.html',{'form':form})
    form.save()
    return redirect('customer_list')

def customer_charge(request,pk):
    queryset = wm.TransactionRecord.objects.filter(customer_id=pk, customer__active=1, active=1).select_related('customer').order_by('-id')
    pager = Pagination(request,queryset)
    form = CustomerChargeForm()
    return render(request,'customer_charge.html',locals())


def customer_charge_add(request,pk):
    res = BaseResponse(status=False)
    form = CustomerChargeForm(request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict)

    amount = form.cleaned_data['amount']
    charge_type = form.cleaned_data['charge_type']

    try:
        with transaction.atomic():
            customer_obj = wm.Customer.objects.filter(active=1,id=pk).select_for_update().first()

            if charge_type==2 and customer_obj.balance<amount:
                return JsonResponse(
                    {'status': False, 'detail': {"amount": ["余额不足，账户总余额只有:{}".format(customer_obj.balance)]}})

            if charge_type==1:
                customer_obj.balance += amount
            else:
                customer_obj.balance -= amount

            customer_obj.save()

            form.instance.customer = customer_obj
            form.instance.creator_id = request.fc_user.id
            form.save()
    except Exception as e:
        return JsonResponse({'status': False, 'detail':{'amount':['操作失败']}})
    return JsonResponse({'status': True})





